$.mobile.defaultPageTransition = 'slide';
var mContacts = {
  $actualizar: null,
  $progressText: null,
  contacts: null,
  changedContacts: [ ],
  contactsSavedCount: 0,
  contactsNotSavedCount: 0,
  contactsPerPage: 150,
  currentPage: null,
  numberOfPages: null,
  resetProcess: function () {
    // save for each page:
    this.numberOfPages = Math.ceil(self.contacts.length / self.contactsPerPage );
    this.currentPage = 1;
    // counters:
    this.contactsSavedCount = 0;
    this.contactsNotSavedCount = 0;
    this.changedContacts = [];
    ProgressBar.set(0);
    this.$progressText.text("");
  },
  visuallySetUpdatingContacts: function ( hide ) {
    if (hide) {
      $(".divs_loading_contacts").fadeOut("fast");
      $(".nowUpdatingContacts").fadeIn("slow");
    }
    else {
      $(".nowUpdatingContacts").fadeOut("fast");
      $(".divs_loading_contacts").fadeIn("slow");
    }
  },
  showResults: function () {
    if ( this.contactsNotSavedCount > 0 ) {
      navigator.notification.alert("Lo sentimos mucho, " + this.contactsNotSavedCount + " no pudieron ser procesados.", (null), "Error");
    }
    else {
      navigator.notification.alert( this.contacts.length + " contactos fueron procesados.", null, "¡Felicidades!");
    }
    this.visuallySetUpdatingContacts( false );
  },
  checkForContactsFinished: function () {
    var processedContacts = (this.contactsSavedCount + this.contactsNotSavedCount);
    ProgressBar.set(processedContacts);
    this.$progressText.text( "procesando contacto " + processedContacts + " de " + this.contacts.length );
    if ( processedContacts >= this.contacts.length ) {
      this.showResults();
    }
    if ( processedContacts >= ( this.currentPage * this.contactsPerPage ) ) {
      ++this.currentPage;
      this.saveNewNumbers();
    }
  },
  contactAlreadySaved: function ( contact ) {
    var self = mContacts;
    ++self.contactsSavedCount;
    self.checkForContactsFinished();
    //console.log("replaced " + contact.id );
  },
  contactNotSaved: function (err) {
    var self = mContacts;
    ++self.contactsNotSavedCount;
    self.checkForContactsFinished();
  },
  saveNewNumbers: function () {
    var fromNumber = ((this.currentPage - 1) * this.contactsPerPage);
    var untilNumber = this.currentPage * this.contactsPerPage;
    //console.log("saving from " + String(fromNumber) + " until " + String(untilNumber) );
    for ( var i = fromNumber; ((i < this.contacts.length) && (i < untilNumber)) ; i++ ) {
      this.contacts[i].save( this.contactAlreadySaved, this.contactNotSaved);
    }
  },
  backupNumbers: function () {
    var backup;
    if (typeof window.localStorage.contactsBackup == "undefined") {
      // it's first time:
      backup = [];
    }
    else {
      // backup exists, backup again.
      backup = JSON.parse( window.localStorage.contactsBackup );
    }
    backup.push(this.changedContacts);
    // stringify and save to localStorage:
    backup = JSON.stringify(backup);
    window.localStorage.setItem("contactsBackup", backup);
    //console.log( "localstorage: " + window.localStorage.getItem("contactsBackup") );
  },
  existsContact: function ( id ) {
    for ( var i = 0; i < this.changedContacts.length; i++ ) {
      if ( this.changedContacts[i].id === id ) {
        return true;
      }
    }
    return false;
  },
  checkAndConvertNumbers: function () {
    //console.log(JSON.stringify(this.contacts));
    var contacts = this.contacts;
    for ( var i=0; i < contacts.length; i++ ) {        // Para cada contacto
      var phoneNumbers = contacts[i].phoneNumbers;
      if (phoneNumbers !== null) {
        for ( var j=0; j < phoneNumbers.length; j++ ) {
          var thisNumber = phoneNumbers[j];
          if ( String( thisNumber.value ).length > 8 ) {
            //console.log("old: " + thisNumber.value);
            var nuevoNumero = validarNumero( thisNumber.value );
            //console.log("new: " + nuevoNumero);
            // add to backup list only if it's not there already:
            if ( !(this.existsContact(contacts[i].id)) ) {
              this.changedContacts.push( contacts[i] );
            }
            thisNumber.value = nuevoNumero;
            //console.log("finishing " + i);
          }
        }
      }
    }
    //console.log("ok");
    var length = this.changedContacts.length;
    //console.log("changing " + length + " contacts");
  },
  wantsToUpdate: function () {
    self = mContacts;
    if (self.contacts.length > 0) {
      navigator.notification.confirm( self.contacts.length + " contactos serán actualizados.", function ( buttonIndex ) {
        if ( buttonIndex == 1 ) {
          // self.$actualizar.attr("disabled","disabled");
          self.resetProcess();

          self.visuallySetUpdatingContacts( true );

          self.checkAndConvertNumbers();
          self.backupNumbers();

          self.saveNewNumbers( );
          // self.showResults();
        }
      }, "Confirmación", "Aceptar,Cancelar");
    }
    else {
      navigator.notification.alert('Lo sentimos, no hemos encontrado ningún contacto en tu agenda.',null,'Hay un problema');
    }
  },
  init: function () {
    this.$actualizar = $("#actualizar");
    this.$progressText = $("#progressbardiv #progressText");
    this.$actualizar.live("click", this.wantsToUpdate);
  }
};

// wait for it to be ready:
function isReady () {
  otherThings();

  mContacts.init();

  getContacts();
  
}

var getContacts = function () {
  function onSuccess (contacts) {
    //console.log("got " + contacts.length + " contacts.");
    $(".waitingContacts").fadeOut();
    $(".divs_loading_contacts").fadeIn();
    mContacts.contacts = contacts;
    ProgressBar.init( contacts.length );
  }
  function onError (error) {
    //console.log("Lo sentimos, hubo un problema al leer los contactos de tu dispositivo");
  }
  var options = new ContactFindOptions();
  options.filter="";
  options.multiple = true;
  var fields = ["id", "displayName", "name", "nickname", "phoneNumbers", "emails", "addresses", "ims", "organizations", "birthday", "note", "photos", "categories", "urls"];
  navigator.contacts.find(fields, onSuccess, onError, options);
  //console.log("looking for contacts..");
};

var otherThings = function () {
  $(".divs_loading_contacts").hide();
  $("#firstScreen").fadeIn("slow");
  $(".removeDivContainer").each( function () {
    $this = $(this);
    $this.insertAfter($this.parent());
  });
  $(".li-menu.main").live("click", function() {
    $this = $(this);
    $this.addClass("active");
    setTimeout( function () {
     $this.removeClass("active");
    }, 1000);
  });
};

var aceptarTerminos = false;
function aceptaCondiciones(){
  if(!aceptarTerminos){
    // document.getElementById('botonera').style.display = 'inline';
    $("#botonera").slideDown("fast");
    $("#firstScreen").animate({
                              marginTop: 0
                              });
    // css("margin-top","0");
    aceptarTerminos = true;
  } else{
    // document.getElementById('botonera').style.display = 'none';
    $("#botonera").slideUp("fast");
    $("#firstScreen").delay(300).css("margin","10% auto");
    aceptarTerminos = false;
  }
}

document.addEventListener("deviceready", isReady, false);